import 'dart:math';

import 'package:flutter/cupertino.dart';

import '../utils/toast.dart';

class MoveAndScaleBox extends StatefulWidget {
  final Widget? child;

  const MoveAndScaleBox({super.key, this.child});

  @override
  State<MoveAndScaleBox> createState() => _MoveAndScaleBoxState();
}

class _MoveAndScaleBoxState extends State<MoveAndScaleBox> {
  Offset _offset = Offset.zero;
  double _scale = 1;
  double _scaleStart = 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Transform.scale(
        scale: _scale,
        child: Transform.translate(
          offset: _offset,
          child: widget.child,
        ),
      ),
      onScaleStart: (ScaleStartDetails details) {
        _scaleStart = _scale;
      },
      onScaleUpdate: (ScaleUpdateDetails details) {
        final tempOffset = details.focalPointDelta;
        setState(() {
          _scale = max(min(_scaleStart * details.scale, 2), 1);
          _offset = Offset(_offset.dx + tempOffset.dx / _scale,
              _offset.dy + tempOffset.dy / _scale);
        });
      },
      onScaleEnd: (ScaleEndDetails details) {
        // 缩放和移动会分别触发
        showToast(msg: '双击还原居中', cancel: true);
      },
      onDoubleTap: () {
        setState(() {
          _offset = Offset.zero;
          _scale = 1;
          _scaleStart = 1;
        });
      },
    );
  }
}
